/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JPanelResumenEvento.java
 *
 * Created on 27-11-2011, 05:53:06 PM
 */
package androidutal;

import com.toedter.calendar.IDateEvaluator;
import com.toedter.calendar.JDateChooser;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import data.dataBase.CalendarioEvento;
import java.awt.Color;
import java.awt.Component;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

/**
 *
 * @author Roberto
 */
public class JPanelResumenEvento extends javax.swing.JPanel {
    private JVentana ventana;
    private String fecha;
     final String[] columnNames1 = {"Hora","Evento"};
     public Date fechaSeleccionada;
    
    /** Creates new form JPanelResumenEvento */
    public JPanelResumenEvento(JVentana ventana) {
        this.ventana=ventana;
        initComponents();
        this.jTable1.getModel();
        Date date =new Date();
        fechaSeleccionada=date;
        this.jDateChooser1.getJCalendar().getDayChooser().addDateEvaluator(new IDateEvaluatorImpl(this.ventana));
        this.jDateChooser1.setDate(date);
        this.jDateChooser1.getJCalendar().getDayChooser().setBackground(Color.yellow);
        fecha= new SimpleDateFormat("dd/MM/yyyy").format(this.getjDateChooser1().getDate());
        this.jBotonEditar.setEnabled(false);
        this.jBotonEliminar.setEnabled(false);
        this.jTable1.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent mouseEvent){
            // Acciones del click sobre la tabla
                JTable tabla= (JTable)mouseEvent.getSource();
                ModeloTabla tm=(ModeloTabla)tabla.getModel();
             
                if (tabla.getSelectedRow()!=-1){
                    if(tm.esBorrador(tabla.getSelectedRow())){
                        //System.out.println(tabla.getValueAt(tabla.getSelectedRow(), 2));
                        jBotonEditar.setEnabled(true);
                        jBotonEliminar.setEnabled(true);
                    }
                    else{
                        jBotonEditar.setEnabled(false);
                        jBotonEliminar.setEnabled(false);
                    }
                }
            }
          });
        
        
    }

    public String getFecha() {
        return fecha;
    }

    public void setFecha(String fecha) {
        this.fecha = fecha;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jBotonAtras = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jDateChooser1 = new com.toedter.calendar.JDateChooser();
        jBotonNuevo = new javax.swing.JButton();
        jBotonEditar = new javax.swing.JButton();
        jBotonEliminar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setBackground(java.awt.Color.black);

        jBotonAtras.setBackground(java.awt.Color.white);
        jBotonAtras.setText("Atras");
        jBotonAtras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotonAtrasActionPerformed(evt);
            }
        });

        jTable1.setModel(new ModeloTabla(this.ventana,this.columnNames1));
        jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jTable1.setSelectionBackground(new java.awt.Color(0, 204, 204));
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTable1MousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jDateChooser1.setDateFormatString("dd/MM/yyyy");
        jDateChooser1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                jDateChooser1MouseExited(evt);
            }
        });
        jDateChooser1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jDateChooser1PropertyChange(evt);
            }
        });

        jBotonNuevo.setBackground(java.awt.Color.white);
        jBotonNuevo.setText("Nuevo");
        jBotonNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotonNuevoActionPerformed(evt);
            }
        });

        jBotonEditar.setBackground(java.awt.Color.white);
        jBotonEditar.setText("Editar");
        jBotonEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotonEditarActionPerformed(evt);
            }
        });

        jBotonEliminar.setBackground(java.awt.Color.white);
        jBotonEliminar.setText("Eliminar");
        jBotonEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBotonEliminarActionPerformed(evt);
            }
        });

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setText("Vista Previa");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(77, 77, 77))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addComponent(jBotonNuevo)
                .addGap(10, 10, 10)
                .addComponent(jBotonEditar)
                .addGap(6, 6, 6)
                .addComponent(jBotonEliminar)
                .addGap(10, 10, 10)
                .addComponent(jButton1)
                .addGap(6, 6, 6)
                .addComponent(jBotonAtras)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addComponent(jDateChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jBotonNuevo)
                    .addComponent(jBotonEditar)
                    .addComponent(jBotonEliminar)
                    .addComponent(jButton1)
                    .addComponent(jBotonAtras)))
        );
    }// </editor-fold>//GEN-END:initComponents

private void jBotonAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotonAtrasActionPerformed
// TODO add your handling code here:
        this.setVisible(false);
        ventana.add(ventana.getMenu(),BorderLayout.CENTER);
        ventana.setBotonSeleccionado();
        this.ventana.getMenu().setVisible(true);
}//GEN-LAST:event_jBotonAtrasActionPerformed

public void cargarDatos()
{
    this.limpiarTabla();
    fecha = new SimpleDateFormat("dd/MM/yyyy").format(fechaSeleccionada);
    if (this.ventana.getBaseDeDatos().getCalendarioEventos(fecha)!=null)
            {
                ArrayList<data.dataBase.CalendarioEvento> temp=this.ventana.getBaseDeDatos().getCalendarioEventos(fecha);
                for(int i=0; temp.size()>i;i++)
                {
                    if(temp.get(i).isBorrador())
                        this.insertarInfo(temp.get(i).getHorario(), temp.get(i).getNombre(),"Si");
                    else
                        this.insertarInfo(temp.get(i).getHorario(), temp.get(i).getNombre(),"No");
                   
                }
                
            } 
}

private void jBotonNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotonNuevoActionPerformed
// TODO add your handling code here:
        this.jDateChooser1.setDate(fechaSeleccionada);
        this.setVisible(false);
        JPanelEvento evento = new JPanelEvento(ventana,this);
        ventana.add(evento,BorderLayout.CENTER);
        evento.setVisible(true);
        
}//GEN-LAST:event_jBotonNuevoActionPerformed

    private void jBotonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotonEditarActionPerformed
        // TODO add your handling code here:
        
        ModeloTabla modelo=(ModeloTabla)this.jTable1.getModel();
        fecha = new SimpleDateFormat("dd/MM/yyyy").format(this.fechaSeleccionada);
        
        if(this.jTable1.getSelectedRow()>=0){
            if( ventana.getBaseDeDatos().getResumenEventos().get(fecha).get(this.jTable1.getSelectedRow()).isBorrador()){
                CalendarioEvento e= ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(this.jTable1.getSelectedRow());
                JPanelEvento jpe=new JPanelEvento(ventana,this);
                jpe.getjTopico().setText(e.getTopico());
                jpe.getjNombre().setText(e.getNombre());
                jpe.getjLugar().setText(e.getLugar());
                jpe.getjObs().setText(e.getObservacion());
                jpe.setHora(e.getHorario());
                if(e.getFile() != null)
                    jpe.getjAdjunto().setText(e.getFile().getAbsolutePath());
                jpe.setFile(e.getFile());
                jpe.setIsBorrador(true);
                jpe.setVisible(true);
                ventana.add(jpe,BorderLayout.CENTER);
                this.setVisible(false);
                //lo remuevo para no tenerlo dos vese
                ventana.getBaseDeDatos().getCalendarioEventos(fecha).remove(this.jTable1.getSelectedRow());
                ventana.save();
                
            }
        }
        
//        if(modelo.getValueAt(this.jTable1.getSelectedRow(), 2).equals("Si")){
//            for(int i =0; i<ventana.getBaseDeDatos().getCalendarioEventos(fecha).size(); i++){
//                if (ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(i).getHorario().equals((String)modelo.getValueAt(this.jTable1.getSelectedRow(), 0))){
//                    CalendarioEvento e= ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(i);
//                    JPanelEvento jpe=new JPanelEvento(ventana,this);
//                    jpe.getjTopico().setText(e.getTopico());
//                    jpe.getjNombre().setText(e.getNombre());
//                    jpe.getjLugar().setText(e.getLugar());
//                    jpe.getjObs().setText(e.getObservacion());
//                    jpe.setHora(e.getHorario());
//                    jpe.setVisible(true);
//                    jpe.getjAdjunto().setText(e.getFile().getAbsolutePath());
//                    jpe.setFile(e.getFile());
//                    jpe.setIsBorrador(true);
//                    ventana.add(jpe,BorderLayout.CENTER);
//                    this.setVisible(false);
//                    //lo remuevo para no tenerlo dos vese
//                    ventana.getBaseDeDatos().getCalendarioEventos(fecha).remove(i);
//                    ventana.save();
//                }
//            }
//        }
        this.cargarDatos();
    }//GEN-LAST:event_jBotonEditarActionPerformed

    private void jBotonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBotonEliminarActionPerformed
        // TODO add your handling code here:
        this.jDateChooser1.setDate(fechaSeleccionada);
        ModeloTabla modelo=(ModeloTabla)this.jTable1.getModel();
        fecha = new SimpleDateFormat("dd/MM/yyyy").format(this.fechaSeleccionada);
        
        if(this.jTable1.getSelectedRow()>=0){
            if( ventana.getBaseDeDatos().getResumenEventos().get(fecha).get(this.jTable1.getSelectedRow()).isBorrador()){
                ventana.getBaseDeDatos().getResumenEventos().get(fecha).remove(this.jTable1.getSelectedRow());
                ventana.save();
                modelo.removeRow(this.jTable1.getSelectedRow());  
            }
        }
        this.cargarDatos();
    }//GEN-LAST:event_jBotonEliminarActionPerformed

private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
// TODO add your handling code here:
   
}//GEN-LAST:event_jTable1MouseReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        ModeloTabla modelo=(ModeloTabla)this.jTable1.getModel();
        this.jDateChooser1.setDate(this.fechaSeleccionada);
        fecha = new SimpleDateFormat("dd/MM/yyyy").format(this.fechaSeleccionada);

        if(this.jTable1.getSelectedRow()!=-1){
            CalendarioEvento e= ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(this.jTable1.getSelectedRow());
                JPanelEvento jpe=new JPanelEvento(ventana,this);
                jpe.getjTopico().setText(e.getTopico());
                jpe.getjNombre().setText(e.getNombre());
                jpe.getjLugar().setText(e.getLugar());
                jpe.getjObs().setText(e.getObservacion());
                jpe.setHora(e.getHorario());
                if(e.getFile() != null)
                    jpe.getjAdjunto().setText(e.getFile().getAbsolutePath());
                jpe.setFile(e.getFile());
                jpe.bloquear();
                jpe.setVisible(true);
                ventana.add(jpe,BorderLayout.CENTER);
                this.setVisible(false);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

private void jDateChooser1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDateChooser1MouseExited
// TODO add your handling code here:
//     this.cargarDatos();
//    this.jDateChooser1.getJCalendar().getDayChooser().addDateEvaluator(new IDateEvaluatorImpl(this.ventana));
    
}//GEN-LAST:event_jDateChooser1MouseExited

private void jTable1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MousePressed
// TODO add your handling code here:
    this.jDateChooser1.setDate(fechaSeleccionada);
}//GEN-LAST:event_jTable1MousePressed

private void jDateChooser1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooser1PropertyChange
// TODO add your handling code here:
    this.fechaSeleccionada=this.jDateChooser1.getDate();
    this.cargarDatos();
}//GEN-LAST:event_jDateChooser1PropertyChange

public void limpiarTabla()
    {
        ModeloTabla modelo=(ModeloTabla) this.jTable1.getModel();
        int row=modelo.getRowCount()-1;
               
        while (row >=0){
            modelo.removeRow(row);
            row=modelo.getRowCount()-1;
        }
        this.jTable1.setModel(modelo);
        
    }
public void addFila(){
        ModeloTabla modelo=(ModeloTabla) this.jTable1.getModel();
        int col=modelo.getRowCount();
        modelo.addRow(new Object[col]);
        TableColumn columna1 = jTable1.getColumnModel().getColumn(0); 
        TableColumn columna2 = jTable1.getColumnModel().getColumn(1); 
//        TableColumn columna3 = jTable1.getColumnModel().getColumn(2); 
        MiRender mr=new MiRender();
        columna1.setCellRenderer(mr);
        columna2.setCellRenderer(mr);
  //      columna3.setCellRenderer(mr);
        this.jTable1.setModel(modelo);
        
    }
public void insertarInfo(String data1, String data2,String data3){
        this.addFila();
        jTable1.setValueAt(data1,jTable1.getRowCount()-1,0);
        jTable1.setValueAt(data2,jTable1.getRowCount()-1,1);
    //    jTable1.setValueAt(data3,jTable1.getRowCount()-1,2);
        
        
    }

    public JDateChooser getjDateChooser1() {
        return jDateChooser1;
    }
    public void setjDateChooser1(JDateChooser date) {
        this.jDateChooser1= date;
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBotonAtras;
    private javax.swing.JButton jBotonEditar;
    private javax.swing.JButton jBotonEliminar;
    private javax.swing.JButton jBotonNuevo;
    private javax.swing.JButton jButton1;
    private com.toedter.calendar.JDateChooser jDateChooser1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    
    public class MiRender extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus,int row, int column){
            super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            ModeloTabla mt=(ModeloTabla)table.getModel();
            if(row<= mt.getRowCount())
            {
                if(mt.esBorrador(row)){
                    this.setOpaque(true);
                    this.setBackground(Color.green);
                    this.setForeground(Color.black);
                }
                else{
                    this.setOpaque(true);
                    this.setBackground(Color.white);
                    this.setForeground(Color.black);
                }
                if(table.getSelectedRow()==row)
                {
                    this.setOpaque(true);
                    this.setBackground(Color.blue);
                    this.setForeground(Color.white);
                }
            }
               
            return this;
        }
    }

    private static class IDateEvaluatorImpl implements IDateEvaluator {
        private JVentana ventana;
        private String fecha;
        public IDateEvaluatorImpl() {
        }

        private IDateEvaluatorImpl(JVentana ventana) {
            this.ventana=ventana;
        }

        @Override
        public boolean isSpecial(Date date) {
            fecha = new SimpleDateFormat("dd/MM/yyyy").format(date);
            if(this.ventana.getBaseDeDatos().getCalendarioEventos(fecha) != null ){
                    if(!this.ventana.getBaseDeDatos().getCalendarioEventos(fecha).isEmpty()){
                        return true;
                    }
            }
            return false;
        }

        @Override
        public Color getSpecialForegroundColor() {
            return Color.black;
        }

        @Override
        public Color getSpecialBackroundColor() {
            return Color.green;
        }

        @Override
        public String getSpecialTooltip() {
            boolean flag=false;
            boolean flag2=false;
            for(int i =0 ; i < this.ventana.getBaseDeDatos().getCalendarioEventos(fecha).size();i ++){
                if (this.ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(i).isBorrador()){
                    flag =true;
                }
                else if(!this.ventana.getBaseDeDatos().getCalendarioEventos(fecha).get(i).isBorrador()){
                    flag2=true;
                }
            }
            if(flag && flag2){
                return "hay eventos y borradores ";
            }
            else if(!flag && flag2){
                return "hay eventos";
            }
            else if(flag && !flag2){
                return "hay borradores";
            }
            return "desocupado";
        }

        @Override
        public boolean isInvalid(Date date) {
            return false;
        }

        @Override
        public Color getInvalidForegroundColor() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public Color getInvalidBackroundColor() {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public String getInvalidTooltip() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}
